#!/usr/bin/env python
# -*- coding: UTF-8 -*-
"""
@Project    :icac2 
@File       :response.py
@Author     :wangfan13
@Date       :2021/5/26 12:42 
"""
from rest_framework import status
from rest_framework.renderers import JSONRenderer
from rest_framework.views import exception_handler
from rest_framework.response import Response
from django.http import JsonResponse

class BaseResponse(object):
    """封装的返回信息类"""

    def __init__(self):
        self.code = 200
        self.data = None
        self.msg = None

    @property
    def dict(self):
        return self.__dict__


class CustomJSONRenderer(JSONRenderer):
    """自定义的渲染器"""

    def render(self, data, accepted_media_type=None, renderer_context=None):
        """
        如果使用这个redner，不同的response将会被包装成{"code":200,"data":"X","msg":"X"}
        使用方法：
        - 全局
        REST_FRAMEWORK = {
            'DEFAULT_RENDERER_CLASSES': ('utils.response.FitJSONRenderer', ),
        }
        - 局部
        class UserCountView(APIView):
            renderer_classes = [FitJSONRenderer]
        :param data:{"msg":"X"}
        :param accepted_media_type:
        :param renderer_context:
        :return:{"code":200,"data":"X","msg":"X"}
        """
        response_body = BaseResponse()
        response = renderer_context.get("response")
        response_body.code = response.status_code
        if response_body.code >= 400:  # 响应异常
            response_body.msg = data['detail'] if 'detail' in data else data
        else:
            response_body.data = data
        renderer_context.get("response").status_code = 200  # 统一成200响应,用code区分
        return super(CustomJSONRenderer, self).render(response_body.dict, accepted_media_type, renderer_context)






class response_result:

    """
    @:param code 0--成功, 2--密码错误， 3--用户不存在， 4--当前账号无权限， 302--未登录，
    """
    @staticmethod
    def res_success(data='', code=0, msg='操作成功'):
          # jr= JsonResponse({'ret': code, "data": data, 'msg': msg}, safe=False)
          # jr.set_cookie("aa", "aa")
        return JsonResponse({'ret': code, "data": data, 'msg': msg}, safe=False)
    """
    @:param code 1--失败,
    """

    @staticmethod
    def res_faile(data='', code=1, msg='操作失败'):
        return JsonResponse({'ret': code, "err": data, 'msg': msg}, safe=False)


    @staticmethod
    def res_total_success(total, data, code=0, msg='操作成功'):
        return JsonResponse({'ret': code, "total": total, "data": data, 'msg': msg}, safe=False)

    # 登录过期  status--302
    @staticmethod
    def res_log_expiry():
        return JsonResponse(dict(), status=302)



def res_log_expiry():
    return JsonResponse('', status=302)